package com.ruoyi.common.annotation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

/**
 * 非空正则校验实现
 */
@Component
public class NotNullPatternValidator implements ConstraintValidator<NotNullPattern, String> {
    private String regexp;

    @Override
    public void initialize(NotNullPattern constraintAnnotation) {
        this.regexp = constraintAnnotation.regexp();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 当值为 null 时跳过验证
        if (value == null) {
            return true;
        }
        // 非空时进行正则验证
        return Pattern.matches(regexp, value);
    }
}

